package com.sjsu.aws.primitve.client.groupmembership;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import org.apache.log4j.Logger;
import com.sjsu.aws.groupmembership.GroupMemberShip;
import com.sjsu.aws.groupmembership.GroupMembershipServiceImpl;
import com.sjsu.aws.utils.TimeUtil;

public class RenewEndTimeThreadGroupMemberShip {
	
	private final static Logger	                  LOG	      = Logger.getLogger(RenewEndTimeThreadGroupMemberShip.class);
	
	private final static ScheduledExecutorService	scheduler	= Executors
	                                                                  .newScheduledThreadPool(1);
	
	public static void main(String[] args) throws Exception {
		long pollingPeriod = 1000;
		startPolling(pollingPeriod);
	}
	
	public static void startPolling(long pollingPeriod) throws Exception {
		LOG.info("Start Polling for GroupMembership Ephemeral Node with pollingPeriod: "
		        + pollingPeriod);
		GroupMembershipServiceImpl groupMembershipServiceImpl = new GroupMembershipServiceImpl();
		pollDB(pollingPeriod, groupMembershipServiceImpl);
	}
	
	public static void pollDB(long pollingPeriod,
	        final GroupMembershipServiceImpl groupMembershipServiceImpl) {
		
		final Runnable watcher = new Runnable() {
			public void run() {
				long timeout = 10000;
				GroupMemberShip g = new GroupMemberShip();
				g.setMemberId("CD");
				g.setEndTimestamp(TimeUtil.getEndTime(timeout));
				try {
					LOG.info("Renew EndTime For EphemeralNode  for GroupMembership");
					groupMembershipServiceImpl.renewEphemeralMembership(g);
				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException(
					        "Error in ephemeral Thread, Error message : "
					                + e.getMessage());
				}
				
			}
		};
		
		final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(
		        watcher, 0, pollingPeriod, MILLISECONDS);
	}
}